package com.blog.admin.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.blog.admin.bean.Role;
import com.blog.admin.bean.RoleMenuMapping;
import com.blog.admin.dao.MenuMapper;
import com.blog.admin.dao.RoleMapper;
import com.blog.admin.service.RoleService;

@Transactional
@Service
public class RoleServiceImpl implements RoleService
{
	@Resource
	RoleMapper roleMapper;
	
	@Resource
	MenuMapper menuMapper;
	public List<Role> queryRoleByUserId(Integer id) 
	{
		return roleMapper.selectRoleByUserId(id);
	}

	public List<Role> queryAllRole() 
	{
		return roleMapper.selectAllRole();
	}

	public Role queryRoleById(Integer id) {
		return roleMapper.selectRoleById(id);
	}

	public Integer addRoleAndRoleMenuMapping(String roleName, String menuIds) {
		Role role = new Role();
		role.setRoleName(roleName);
		roleMapper.insertRole(role);
		if(menuIds!=null && menuIds!="")
		{
			String[] meunIdArray = menuIds.split(",");
			for(String meunId :meunIdArray)
			{
				RoleMenuMapping roleMenuMapping = new RoleMenuMapping();
				roleMenuMapping.setRoleId(role.getId());
				roleMenuMapping.setMenuId(Integer.parseInt(meunId));
				roleMapper.insertRoleMenuMapping(roleMenuMapping);
			}
		}
		return 1;
	}

	public void removeRole(Integer roleId) 
	{
		roleMapper.deleteRoleMenuMappingByUserId(roleId);
		roleMapper.deleteRoleByUserId(roleId);
	}

	public Integer modifyRoleAndRoleMenuMapping(String id,String roleName, String menuIds) {
		roleMapper.updateRoleById(id,roleName);
		roleMapper.deleteRoleMenuMappingByUserId(Integer.parseInt(id));
		if(menuIds!=null && menuIds!="")
		{
			String[] meunIdArray = menuIds.split(",");
			for(String meunId :meunIdArray)
			{
				RoleMenuMapping roleMenuMapping = new RoleMenuMapping();
				roleMenuMapping.setRoleId(Integer.parseInt(id));
				roleMenuMapping.setMenuId(Integer.parseInt(meunId));
				roleMapper.insertRoleMenuMapping(roleMenuMapping);
			}
		}
		return 1;
	}

}
